import type { IMenu } from "@/layout/sidebar/SubMenu.vue";
import { asyncRoutes, CONSTROUTER } from '@/router'
import { omit } from "lodash-es";
import type { RouteRecordRaw } from 'vue-router';

type IMenuMap = Record<string, IMenu>

export function useDynamicRoutes(menus: IMenu[]) {
  const menuMap = genMenuMap(menus)
  const dynamicRoutes = genDynamicRoutes(asyncRoutes.children, menuMap)
  const rootRoute = omit(asyncRoutes, ['children']) as RouteRecordRaw
  rootRoute.children = [...dynamicRoutes, ...CONSTROUTER]
  rootRoute.redirect = rootRoute.path + dynamicRoutes[0].path
  return rootRoute
}

function genMenuMap(menus: IMenu[]) {
  return menus.reduce((menuMap, menu) => {
    const { component, childList } = menu
    if (component) {
      menuMap[component] = menu
    }
    if (childList && childList.length > 0) {
      menuMap = { ...menuMap, ...genMenuMap(childList) }
    }
    return menuMap
  }, {} as IMenuMap)
}

function genDynamicRoutes(routes: RouteRecordRaw[], remoteMenuMap: IMenuMap) {
  const result: RouteRecordRaw[] = []
  routes.forEach(route => {
    const url = `/${route.path}`
    const menu = remoteMenuMap[url]
    if (menu) {
      const { name, parentId } = menu
      if (route.meta) {
        route.meta.title = name
        route.meta.parentId = parentId
      }
      result.push(route)
    }
  })
  return result
}